package com.clwl.supervise.superviseapp.service.company;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clwl.supervise.superviseapp.beans.company.CompanySearchParams;
import com.clwl.supervise.superviseapp.beans.company.SimpleCompany;
import com.clwl.supervise.superviseapp.beans.company.UpdateCompanyPortraitParams;
import com.clwl.supervise.superviseapp.entity.base.*;
import com.clwl.supervise.superviseapp.entity.pro.JgTcCompany;
import com.clwl.supervise.superviseapp.entity.supervise.JgClassifyCyfw;
import com.clwl.supervise.superviseapp.entity.supervise.JgClassifySpxs;
import com.clwl.supervise.superviseapp.entity.supervise.JgGrid;
import com.clwl.supervise.superviseapp.mapper.base.JgProcessCodeMapper;
import com.clwl.supervise.superviseapp.mapper.base.TcCompanyMapper;
import com.clwl.supervise.superviseapp.mapper.base.TcCompanyModifyRecordMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsDeptMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgClassifyCyfwMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgClassifySpxsMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgGridMapper;
import com.clwl.supervise.superviseapp.util.CompanyProcessUtil;
import com.clwl.supervise.superviseapp.util.UserHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.*;

@Service
public class TcCompanyService extends ServiceImpl<TcCompanyMapper, TcCompany> {
    @Autowired
    TcCompanyMapper tcCompanyMapper;
    @Autowired
    JgClassifySpxsMapper jgClassifySpxsMapper;
    @Autowired
    JgClassifyCyfwMapper jgClassifyCyfwMapper;
    @Autowired
    JgProcessCodeMapper jgProcessCodeMapper;
    @Autowired
    TcCompanyModifyRecordMapper tcCompanyModifyRecordMapper;
    @Autowired
    JgGridMapper jgGridMapper;
    @Autowired
    TsDeptMapper tsDeptMapper;

    public Page<JgTcCompany> selectProList(Integer pageNum, Integer pageSize,CommonSearchEntity commonSearchEntity){
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        String deptType = "3";
        if ("0".equals(UserHelper.getUserInfo().getDataRange())){
            deptType = "0";
        } else if ("1".equals(UserHelper.getUserInfo().getDataRange())){
            deptType = "1";
        } else if ("2".equals(UserHelper.getUserInfo().getDataRange())){
            deptType = "2";
        } else if ("3".equals(UserHelper.getUserInfo().getDataRange())){
            deptType = "2";
        }
        TsDept dataDeptEntity = tsDeptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
        if (dataDeptEntity != null){
            commonSearchEntity.setDataDeptId(dataDeptEntity.getId());
        } else {
            commonSearchEntity.setDataDeptId(UserHelper.getUserInfo().getDeptId());
        }
        commonSearchEntity.setDeptId(UserHelper.getUserInfo().getDeptId());
        commonSearchEntity.setDataRange(UserHelper.getUserInfo().getDataRange());
        commonSearchEntity.setIsSc("1");
        List<String> processList = CompanyProcessUtil.getUserProcessList();
        commonSearchEntity.setProcessList(processList);
        Page<JgTcCompany> page = null;
        if(StringUtils.equals("1",commonSearchEntity.getType())){
            //检查完成列表
            page = tcCompanyMapper.selectCompleteProList(iPage, commonSearchEntity);
        } else {
            page = tcCompanyMapper.selectProList(iPage, commonSearchEntity);
        }

        return page;
    }


    public List<SimpleCompany> selectCompanyList(Integer pageNum, Integer pageSize, CompanySearchParams params) {
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        String dataRange = UserHelper.getUserInfo().getDataRange();
        params.setUserId(UserHelper.getUserId());
        params.setDataRange(dataRange);
        params.setDeptId(UserHelper.getUserInfo().getDeptId());
        params.setBusinessFormatRange(UserHelper.getUserInfo().getBusinessFormatRange());
        String deptType = "3";
        if ("0".equals(dataRange)){
            deptType = "0";
        } else if ("1".equals(dataRange)){
            deptType = "1";
        } else if ("2".equals(dataRange)){
            deptType = "2";
        } else if ("3".equals(dataRange)){
            deptType = "2";
        }
        TsDept dataDeptEntity = tsDeptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
        if (dataDeptEntity != null){
            params.setDataDeptId(dataDeptEntity.getId());
        } else {
            params.setDataDeptId(UserHelper.getUserInfo().getDeptId());
        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("2") >= 0 || UserHelper.getUserInfo().getBusinessFormatRange().indexOf("3") >= 0){
            params.setIsSc("1");
        } else {
            params.setIsSc("0");
        }
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);

        List<String> processList = CompanyProcessUtil.getUserProcessList();
        params.setProcessList(processList);
        IPage<SimpleCompany> page = tcCompanyMapper.selectCompanyList(iPage, params);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return new ArrayList<>();
        }
        return page.getRecords();
    }

    /**
     * 获取企业列表通过企业类型
     * @param pageNum
     * @param pageSize
     * @param typeCode  企业类型
     * @return
     */
    public List<Map<String, Object>> getCompanyByType(Integer pageNum, Integer pageSize, String typeCode ) {
        Map<String,Object> params = new HashMap<>();
        params.put("userId",UserHelper.getUserId());
        params.put("dataRange",UserHelper.getUserInfo().getDataRange());
        params.put("deptId",UserHelper.getUserInfo().getDeptId());
        params.put("typeCode", typeCode);
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        List<String> processList = CompanyProcessUtil.getUserProcessList();
        params.put("processList", processList);
        return tcCompanyMapper.selectCompanyByType(params );
    }
    public TcCompany getTcCompanyById(Long id) {
        TcCompany tcCompany = tcCompanyMapper.selectById(id);
        if (null == tcCompany) {
            return null;
        }
        List<JgProcessCode> plist = jgProcessCodeMapper.findJgProcessCodeByCode(tcCompany.getSupProcess());
        if (!CollectionUtils.isEmpty(plist)) {
            JgProcessCode jgProcessCode = plist.get(0);
            tcCompany.setSuperviseLink(jgProcessCode.getName());
        }
        if (null != tcCompany.getGridId()) {
            //获取网格信息
            JgGrid jgGrid = jgGridMapper.selectById(tcCompany.getGridId());
            if (null == jgGrid) {
                tcCompany.setGridHeadName("无");
            }
            StringBuffer hnBuffer = new StringBuffer();
            if (StringUtils.isNotBlank(jgGrid.getGridPerson1Name())) {
                hnBuffer.append(jgGrid.getGridPerson1Name());
            }
            if (StringUtils.isNotBlank(jgGrid.getGridPerson2Name())) {
                if (hnBuffer.length() <= 0) {
                    hnBuffer.append(jgGrid.getGridPerson2Name());
                } else {
                    hnBuffer.append(",");
                    hnBuffer.append(jgGrid.getGridPerson2Name());
                }
            }
            if (hnBuffer.length() <= 0) {
                hnBuffer.append("无");
            }
            tcCompany.setGridHeadName(hnBuffer.toString());
        } else {
            tcCompany.setGridHeadName("无");
        }
/**
 * 许可证-状态码(
 * 经营企业:1核发 2变更 3换证 4延续 5补发 6注销 7撤销 8吊销  ；
 * 生产企业:1核发 2换证 3变更 4延续 5补领 6注销 7吊销)
 */
        String licenseStat = "";
        String businessCategory = "";
        switch (tcCompany.getSupProcess()) {
            case "spxs":
                licenseStat= getJyLicenseStat(tcCompany.getLicenseStat());
                JgClassifySpxs jgClassifySpxs = jgClassifySpxsMapper.findJgClassifySpxsById(tcCompany.getCompanyTypeId());
                if (null != jgClassifySpxs) {
                    businessCategory = jgClassifySpxs.getName();
                }
                break;
            case "cyfw":
                licenseStat= getJyLicenseStat(tcCompany.getLicenseStat());
                JgClassifyCyfw jgClassifyCyfw = jgClassifyCyfwMapper.findJgClassifyCyfwById(tcCompany.getCompanyTypeId());
                if (null != jgClassifyCyfw) {
                    businessCategory = jgClassifyCyfw.getName();
                }
                break;
            case "spsc":
                licenseStat= getScLicenseStat(tcCompany.getLicenseStat());
                businessCategory = tcCompanyMapper.getScbusinessCategory(tcCompany.getId());
                break;
            case "tssc":
                licenseStat= getScLicenseStat(tcCompany.getLicenseStat());
                businessCategory = tcCompanyMapper.getScbusinessCategory(tcCompany.getId());
                break;
        }
        if (StringUtils.isNotBlank(businessCategory)) {
            tcCompany.setBusinessCategory(businessCategory);
        } else {
            tcCompany.setBusinessCategory("无");
        }
        if (StringUtils.isNotBlank(licenseStat)) {
            tcCompany.setLicenseStat(licenseStat);
        } else {
            tcCompany.setLicenseStat("无");
        }

        return tcCompany;
    }

    /**
     * 许可证-状态码(
     * 生产企业:1核发 2换证 3变更 4延续 5补领 6注销 7吊销)
     */
    private String getScLicenseStat(String licenseStat) {
        if (StringUtils.isBlank(licenseStat)) {
            return "无";
        }

        switch (licenseStat) {
            case "1":
                return "核发";
            case "2":
                return "换证";
            case "3":
                return "变更";
            case "4":
                return "延续";
            case "5":
                return "补领";
            case "6":
                return "注销";
            case "7":
                return "吊销";
            default:
                return "无";
        }
    }

    /**
     * 许可证-状态码(
     * 经营企业:1核发 2变更 3换证 4延续 5补发 6注销 7撤销 8吊销  ；）
     */
    private String getJyLicenseStat(String licenseStat) {
        {
            if (StringUtils.isBlank(licenseStat)) {
                return "无";
            }

            switch (licenseStat) {
                case "1":
                    return "核发";
                case "2":
                    return "变更";
                case "3":
                    return "换证";
                case "4":
                    return "延续";
                case "5":
                    return "补发";
                case "6":
                    return "注销";
                case "7":
                    return "撤销";
                case "8":
                    return "吊销";
                default:
                    return "无";
            }
        }
    }

    public boolean dimension(Long id, String lngLat) {
        TcCompany tcCompany = tcCompanyMapper.selectById(id);
        if (null == tcCompany) {
            return false;
        }
        tcCompany.setLngLat(lngLat);
        tcCompany.setMarkStat("0");
        int flag = tcCompanyMapper.updateById(tcCompany);
        if (0 == flag) {
            return false;
        }
        return true;
    }

    /**
     * 修改主体画像信息
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCompanyPortrait(UpdateCompanyPortraitParams params) {
        TcCompany oldCompany = tcCompanyMapper.selectById(params.getId());
        TcCompanyModifyRecord tcCompanyModifyRecord = new TcCompanyModifyRecord();
        if (params.getIsGongpi() != null) {
            tcCompanyModifyRecord.setUpdateField("是否农产品批发市场");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getIsGongpi());
            tcCompanyModifyRecord.setAfterValue(params.getIsGongpi());
            tcCompanyModifyRecord.setUpdateFieldName("is_gongpi");

            oldCompany.setIsGongpi(params.getIsGongpi());
        }
        if (params.getIsMingchu() != null) {
            tcCompanyModifyRecord.setUpdateField("是否实施“明厨亮灶”工程");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getIsMingchu());
            tcCompanyModifyRecord.setAfterValue(params.getIsMingchu());
            tcCompanyModifyRecord.setUpdateFieldName("is_mingchu");

            oldCompany.setIsMingchu(params.getIsMingchu());
        }
        if (params.getIsXiaoyuan() != null) {
            tcCompanyModifyRecord.setUpdateField("位于校园及其周边");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getIsXiaoyuan());
            tcCompanyModifyRecord.setAfterValue(params.getIsXiaoyuan());
            tcCompanyModifyRecord.setUpdateFieldName("is_xiaoyuan");

            oldCompany.setIsXiaoyuan(params.getIsXiaoyuan());
        }
        if (params.getIsYbz() != null) {
            tcCompanyModifyRecord.setUpdateField("仅售预包装食品");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getIsYbz());
            tcCompanyModifyRecord.setAfterValue(params.getIsYbz());
            tcCompanyModifyRecord.setUpdateFieldName("is_ybz");

            oldCompany.setIsYbz(params.getIsYbz());
        }
        if (params.getIsTeshi() != null) {
            tcCompanyModifyRecord.setUpdateField("含特殊食品销售");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getIsTeshi());
            tcCompanyModifyRecord.setAfterValue(params.getIsTeshi());
            tcCompanyModifyRecord.setUpdateFieldName("is_teshi");

            oldCompany.setIsTeshi(params.getIsTeshi());
        }
        if (params.getAnnualIncome() != null) {
            tcCompanyModifyRecord.setUpdateField("年收入");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getAnnualIncome()+"");
            tcCompanyModifyRecord.setAfterValue(params.getAnnualIncome()+"");
            tcCompanyModifyRecord.setUpdateFieldName("annual_income");
            oldCompany.setAnnualIncome(params.getAnnualIncome());
        }
        if (params.getSamplingScore() != null) {
            tcCompanyModifyRecord.setUpdateField("抽样评分");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getSamplingScore()+"");
            tcCompanyModifyRecord.setAfterValue(params.getSamplingScore()+"");
            tcCompanyModifyRecord.setUpdateFieldName("sampling_score");
            oldCompany.setSamplingScore(params.getSamplingScore());
        }
        if (params.getAppointmentScore() != null) {
            tcCompanyModifyRecord.setUpdateField("预约评分");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getAppointmentScore()+"");
            tcCompanyModifyRecord.setAfterValue(params.getAppointmentScore()+"");
            tcCompanyModifyRecord.setUpdateFieldName("appointment_score");
            oldCompany.setAppointmentScore(params.getAppointmentScore());
        }
        if (params.getPersonTotal() != null) {
            tcCompanyModifyRecord.setUpdateField("员工数");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getPersonTotal()+"");
            tcCompanyModifyRecord.setAfterValue(params.getPersonTotal()+"");
            tcCompanyModifyRecord.setUpdateFieldName("person_total");
            oldCompany.setPersonTotal(params.getPersonTotal());
        }
        if (params.getIsYichang() != null) {
            tcCompanyModifyRecord.setUpdateField("是否异常");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getIsYichang());
            tcCompanyModifyRecord.setAfterValue(params.getIsYichang());
            tcCompanyModifyRecord.setUpdateFieldName("is_yichang");
            oldCompany.setIsYichang(params.getIsYichang());
        }
        if (params.getTeshiLeixing() != null) {
            tcCompanyModifyRecord.setUpdateField("特食类型");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getTeshiLeixing());
            tcCompanyModifyRecord.setAfterValue(params.getTeshiLeixing());
            tcCompanyModifyRecord.setUpdateFieldName("teshi_leixing");
            oldCompany.setTeshiLeixing(params.getTeshiLeixing());
        }
        if (params.getMingchuLx() != null) {
            tcCompanyModifyRecord.setUpdateField("“明厨亮灶”工程类型");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getMingchuLx());
            tcCompanyModifyRecord.setAfterValue(params.getMingchuLx());
            tcCompanyModifyRecord.setUpdateFieldName("mingchu_lx");
            oldCompany.setMingchuLx(params.getMingchuLx());
        }

        if (params.getIsShezuo() != null) {
            tcCompanyModifyRecord.setUpdateField("“是否设座小餐饮");
            tcCompanyModifyRecord.setBeforeValue(oldCompany.getIsShezuo());
            tcCompanyModifyRecord.setAfterValue(params.getIsShezuo());
            tcCompanyModifyRecord.setUpdateFieldName("is_shezuo");
            oldCompany.setIsShezuo(params.getIsShezuo());
        }

        if (this.updateById(oldCompany)) {
            tcCompanyModifyRecord.setCompanyId(oldCompany.getId());
            TsUser user = UserHelper.getUserInfo();
            tcCompanyModifyRecord.setCreator(user.getName());
            tcCompanyModifyRecord.setCreatorId(user.getId());
            tcCompanyModifyRecord.setDeleteFlag(0L);
            tcCompanyModifyRecord.setCreateTime(new Date());
            tcCompanyModifyRecord.setReason(params.getReason());
            tcCompanyModifyRecordMapper.insert(tcCompanyModifyRecord);

            return true;
        }
        tcCompanyMapper.updateById(oldCompany);
        return false;
    }


    public boolean saveUpdateInfo(Long companyId, String fieldName, String fieldValue) {
        TcCompany company = tcCompanyMapper.selectById(companyId);
        //通过反射机制修改fieldName对应的字段名的值
        try {
            Field field = company.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(company, fieldValue);
        } catch (NoSuchFieldException e) {
            log.error("修改字段内容失败:{}",e);
            return false;
        } catch (IllegalAccessException e) {
            log.error("修改字段内容失败:{}",e);
            return false;
        }
        tcCompanyMapper.updateById(company);
        return true;
    }
}
